package org.amj.wn.sect;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.amj.wn.Property;

/**
 * Servlet Filter implementation class AdminFilter
 */
public class SectFilter implements Filter {

	private FilterConfig fConfig;
	private static final String SECT_USER = "sectuser";

	private static class LoginInfo {
		String user;
		String pass;
		
	}
	
	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		LoginInfo opt = getLoginInfo((HttpServletRequest) request);
		
	    if (!login(opt, (HttpServletRequest) request)) {
	    	fConfig.getServletContext().getRequestDispatcher("/sect/login.jsp").forward(request, response);
	    } else {
			chain.doFilter(request, response);
	    }
	}
	
	public static boolean isUserLoggedIn(HttpServletRequest request) {
		return request.getSession().getAttribute(SECT_USER) != null;
	}
	
	public static String getUserId(HttpServletRequest request) {
		return (String) request.getSession().getAttribute(SECT_USER);
	}
	
	private boolean login(LoginInfo opt, HttpServletRequest request) {
		
		if(isUserLoggedIn(request))
			return true;
		if(opt == null)
			return false;
		
		SectWaqfeNau sectWaqfeNau = SectWaqfeNau.get(opt.user);
		
		boolean success = sectWaqfeNau != null && opt.pass != null && opt.pass.equals(sectWaqfeNau.getPassCode());
		
		if(success)
			request.getSession().setAttribute(SECT_USER, opt.user);
		
		return success;
	}

	private LoginInfo getLoginInfo(HttpServletRequest req) {
		if(!"LOGIN".equals(req.getParameter("opt")))
			return null;
		LoginInfo opt = new LoginInfo();
		opt.user = req.getParameter(Property.memberCode.name());
		opt.pass = req.getParameter(Property.passCode.name());

		return opt;
	}

	
	
	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		this.fConfig = fConfig;
		
	}

}
